package com.tinyproxy;

import com.tinyproxy.common.Cfg;
import com.tinyproxy.common.Kits;
import com.tinyproxy.common.LogbackCfg;
import com.tinyproxy.local.LocalServer;
import com.tinyproxy.remote.RemoteServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class TinyProxy {

    final static Logger log;

    public static void main(String[] args) throws IOException {
        String prefix = Kits.executablePrefix();
        if (Kits.isBlank(prefix)) {
            System.out.println("--Can't extract executable path!!!");
            return;
        }

        File cfgFile = new File(prefix + ".cfg");
        log.info("Start to read config file: {}", cfgFile.getAbsolutePath());
        Cfg cfg = Cfg.load(cfgFile);
        if (cfg == null) {
            cfg = new Cfg();
            cfg.save(cfgFile);
            log.info("Can't read config file, generate a default one: {}", cfg);
        } else {
            log.info("Success to load config: {}", cfg);
        }

        if (cfg.isRemote()) {
            new RemoteServer(cfg, log).start();
        } else {
            new LocalServer(cfg, log).start();
        }
    }

    static {
        LogbackCfg.start();
        log = LoggerFactory.getLogger("");
    }

}
